#include <iostream>
#include "httplib.h"
#include "add_contact.pb.h"
#include "ContactsException.h"
#include "Utils.h"


using std::cerr;
using std::cout;
using std::endl;
using namespace httplib;

void printContact(add_contact::AddContactRequest& req) {
    cout << "联系人姓名：" << req.name() << endl;
    cout << "联系人年龄：" << req.age() << endl;
    for (int j = 0; j < req.phone_size(); j++) {
        const add_contact::AddContactRequest_Phone& phone = req.phone(j);
        cout << "联系人电话" << j + 1 << "：" << phone.number();
        cout << "   (" << phone.PhoneType_Name(phone.type()) << ")" << endl;
        // phone.type()返回的是枚举的值
        // PhoneType_Name()将枚举值转换成枚举名
    }
}

int main() {
    cout << "----------服务器启动----------" << endl;
    Server server;

    server.Post("/contacts/add",
        [](const Request& req, Response& res) {
            cout << "接收到post请求！" << endl;
            // 反序列化 request：req.body
            add_contact::AddContactRequest request;
            add_contact::AddContactResponse response;
            try {
                if (!request.ParseFromString(req.body)) {
                    throw ContactsException("AddContactRequest反序列化失败！");
                }

                // 新增联系人
                printContact(request);

                // 构造 response：res.body
                response.set_success(true);
                response.set_uid(Utils::generate_hex(10));

                // res.body
                std::string response_str;
                if (!response.SerializeToString(&response_str)) {
                    throw ContactsException("AddContactResponse序列化失败！");
                }
                res.status = 200;
                res.body = response_str;
                res.set_header("Content-Type", "application/protobuf");
            }
            catch (const ContactsException& e) {
                res.status = 500;
                response.set_success(false);
                response.set_error_desc(e.what());
                std::string response_str;
                if (response.SerializeToString(&response_str)) {
                    res.body = response_str;
                    res.set_header("Content-Type", "application/protobuf");
                }
                cout << "/contacts/add 发生异常，异常信息：" << e.what() << endl;
            }

        });

    server.Get("/test-get",
        [](const Request& req, Response& res) {
            cout << "接收到get请求！" << endl;
            res.status = 200;
        });

    // 绑定8888端口，将端口号对外开放
    server.listen("0.0.0.0", 8888);

    return 0;
}
